import string
import random
import web

from sqlalchemy.orm import scoped_session, sessionmaker
from saSimple_model import *

urls = (
        "/","add",
        "/view","view"
)
web.config.debug
web.config.debug = True               


# web.webapi.internalerror = web.debugerror 
# web.webapi.internalerror = web.debugerror

app = web.application(urls, locals())

def load_sqla(handler):
    web.ctx.orm = scoped_session(sessionmaker(bind=engine))
    try:
        return handler()
    except:
        web.ctx.orm.rollback()
        raise
    finally:
        web.ctx.orm.commit()
app.add_processor(load_sqla)

class add:
    def GET(self):
        web.header('Content-type', 'text/html')
        fname = "".join(random.choice(string.letters)for i in range(4))
        lname = "".join(random.choice(string.letters)for i in range(7))
        u= User(name=fname,
                fullname = fname + ' ' + lname,
                password = 542)
        # web.ctx.orm.add(u)
        web.ctx.orm.save(u)  #docs incorrectly said 'new' instead 'save'
        # return str(dir(web.ctx.orm))
        return 'added ' + web.websafe(str(u)) \
                    + "<br/>" \
                    + "<a href='/view'>view all</a>"
class view:
    def GET(self):
        ret = ""
        # x = 1/0 # delib. error
        web.header('Content-type', 'text/html')
        # return "\n".join(map(str, web.ctx.orm.query(User).all()))
        for u in web.ctx.orm.query(User).all(): ret += (str(u) + "<br/>")
        return ret

                        
if __name__ == "__main__":
    app.run() # works
    # web.run(urls, globals(), web.reloader) #doesnt work
    # app.run(urls, globals(), web.reloader) # no reloader att.
    # app.run(urls) # tuple not callable